package copy.com;


import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 **/
@Slf4j
@ResponseBody
@ControllerAdvice(annotations = {RestController.class, Controller.class})
public class GlobalExceptionHandler {
    //异常包含重复的条目Duplicate entry
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> EQ(SQLIntegrityConstraintViolationException ex) {
        if (ex.getMessage().contains("Duplicate entry")) {
            String[] split = ex.getMessage().split(" ");
              String s = split[2] + "：已存在，全局异常处理";
            return R.error(s);
        }
        return R.error("未知错误");
    }

    @ExceptionHandler(CustomException.class)
    public R<String> EQ(CustomException cu) {
        log.info("抛出一个自定义异常，全局异常处理");
        return R.error(cu.getMessage());
    }
}
